#include <Arduino.h>
#include "TFT_eSPI.h"
#include "drv_tft.h"
#include "lvgl_gui.h"
#include "lvgl.h"

#define SCREEN_WIDTH         160
#define SCREEN_HIGHT         80

static lv_disp_draw_buf_t draw_buf;
static lv_color_t buf[SCREEN_WIDTH * SCREEN_HIGHT];
static lv_obj_t *tileview;
static lv_disp_drv_t disp_drv;

static void load_main_page(lv_obj_t *src);
static void load_wifi_info_page(lv_obj_t *src);
static void load_device_info_page(lv_obj_t *src);

static void lv_disp_flush(lv_disp_drv_t *disp, const lv_area_t *area, lv_color_t *color_p) {
  uint32_t w = (area->x2 - area->x1 + 1);
  uint32_t h = (area->y2 - area->y1 + 1);
  tft.setAddrWindow(area->x1, area->y1, w, h);
  tft.pushColors((uint16_t *)&color_p->full, w * h);
  lv_disp_flush_ready(disp);
}

void gui_init(void) {
  lv_init();
  lv_disp_draw_buf_init(&draw_buf, buf, NULL, SCREEN_WIDTH * SCREEN_HIGHT);
  
  lv_disp_drv_init(&disp_drv);
  disp_drv.hor_res = SCREEN_WIDTH;
  disp_drv.ver_res = SCREEN_HIGHT;
  disp_drv.flush_cb = lv_disp_flush;
  disp_drv.draw_buf = &draw_buf;
  lv_disp_drv_register(&disp_drv);

  lv_obj_clean(lv_scr_act());
  tileview = lv_tileview_create(lv_scr_act());
  lv_obj_set_size(tileview, 160, 80);
  lv_obj_t *tv0 = lv_tileview_add_tile(tileview, 0, 0, LV_DIR_HOR);
  lv_obj_t *tv1 = lv_tileview_add_tile(tileview, 1, 0, LV_DIR_HOR);
  lv_obj_t *tv2 = lv_tileview_add_tile(tileview, 2, 0, LV_DIR_HOR);

  load_main_page(tv0);
  load_wifi_info_page(tv1);
  load_device_info_page(tv2);
}

static void load_main_page(lv_obj_t *src) {
  lv_obj_t * label1 = lv_label_create(src);
  lv_label_set_text(label1, "page 1");
  lv_obj_align(label1, LV_ALIGN_TOP_LEFT, 0, 0); // 居中对齐文本
}

static void load_wifi_info_page(lv_obj_t *src) {
  lv_obj_t * label1 = lv_label_create(src);
  lv_label_set_text(label1, "page 2");
  lv_obj_align(label1, LV_ALIGN_TOP_LEFT, 0, 0); // 居中对齐文本
}

static void load_device_info_page(lv_obj_t *src) {
  lv_obj_t * label1 = lv_label_create(src);
  lv_label_set_text(label1, "page 3");
  lv_obj_align(label1, LV_ALIGN_TOP_LEFT, 0, 0); // 居中对齐文本
}

void gui_switch_page(uint8_t num) {
  lv_obj_set_tile_id(tileview, num, 0, LV_ANIM_ON);
}
